package com.example.homeworktagger.service;

import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;

@Slf4j
@Service
public class HomeworkTagService {

    private final ChatLanguageModel deepseekModel;
    private final ChatLanguageModel qwenModel;

    @Data
    public static class TagResult {
        private String initialTags;
        private String finalTags;
        private long deepseekDuration;
        private long qwenDuration;
        private String homeworkContent;
    }

    public HomeworkTagService(
            @Qualifier("deepseekModel") ChatLanguageModel deepseekModel,
            @Qualifier("qwenModel") ChatLanguageModel qwenModel) {
        this.deepseekModel = deepseekModel;
        this.qwenModel = qwenModel;
    }

    public TagResult generateTags(String homeworkContent) {
        TagResult result = new TagResult();
        result.setHomeworkContent(homeworkContent);

        // 第一步：使用DeepSeek模型生成初始标签
        Instant startTime = Instant.now();
        String initialPrompt = String.format("你是一位资深的小学老师，请给这份作业打一些学习标签，产出不低于10个有序排列的推荐标签，要求返回的数据只输出标签，不要输出多余的数据，标签格式参考：#标签1#标签2\n\n作业内容：%s", homeworkContent);
        String initialTags = deepseekModel.generate(initialPrompt);
        Duration deepseekDuration = Duration.between(startTime, Instant.now());
        result.setDeepseekDuration(deepseekDuration.toMillis());
        result.setInitialTags(initialTags);
        log.info("DeepSeek模型调用耗时：{}ms，返回标签：{}", deepseekDuration.toMillis(), initialTags);

        // 第二步：使用通义千问模型优化标签
        startTime = Instant.now();
        String optimizationPrompt = String.format("你是一位资深的小学老师，请检查一下这份作业：%s对应的学习标签：%s，请选择匹配性最优的5个标签，要求返回的数据只输出标签，不要输出多余的数据，标签格式参考：#标签1#标签2", 
            homeworkContent, initialTags);
        String finalTags = qwenModel.generate(optimizationPrompt);
        Duration qwenDuration = Duration.between(startTime, Instant.now());
        result.setQwenDuration(qwenDuration.toMillis());
        result.setFinalTags(finalTags);
        log.info("通义千问模型调用耗时：{}ms，返回标签：{}", qwenDuration.toMillis(), finalTags);

        return result;
    }
} 